// 时间格式化工具函数

/**
 * 格式化相对时间（几秒前、几分钟前、几小时前等）
 * @param dateString 时间字符串
 * @returns 格式化后的相对时间字符串
 */
export function formatRelativeTime(dateString: string): string {
  if (!dateString) return ''
  
  const now = new Date()
  const date = new Date(dateString)
  const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000)
  
  if (diffInSeconds < 0) {
    return '刚刚'
  }
  
  if (diffInSeconds < 60) {
    return `${diffInSeconds}秒前`
  }
  
  const diffInMinutes = Math.floor(diffInSeconds / 60)
  if (diffInMinutes < 60) {
    return `${diffInMinutes}分钟前`
  }
  
  const diffInHours = Math.floor(diffInMinutes / 60)
  if (diffInHours < 24) {
    return `${diffInHours}小时前`
  }
  
  const diffInDays = Math.floor(diffInHours / 24)
  if (diffInDays < 7) {
    return `${diffInDays}天前`
  }
  
  const diffInWeeks = Math.floor(diffInDays / 7)
  if (diffInWeeks < 4) {
    return `${diffInWeeks}周前`
  }
  
  const diffInMonths = Math.floor(diffInDays / 30)
  if (diffInMonths < 12) {
    return `${diffInMonths}个月前`
  }
  
  const diffInYears = Math.floor(diffInDays / 365)
  return `${diffInYears}年前`
}

/**
 * 格式化绝对时间
 * @param dateString 时间字符串
 * @param format 格式类型
 * @returns 格式化后的时间字符串
 */
export function formatAbsoluteTime(
  dateString: string, 
  format: 'date' | 'datetime' | 'time' = 'datetime'
): string {
  if (!dateString) return ''
  
  const date = new Date(dateString)
  
  switch (format) {
    case 'date':
      return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      })
    case 'time':
      return date.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
    case 'datetime':
    default:
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
  }
}

/**
 * 获取时间状态（今天、昨天、本周、本月等）
 * @param dateString 时间字符串
 * @returns 时间状态字符串
 */
export function getTimeStatus(dateString: string): string {
  if (!dateString) return ''
  
  const now = new Date()
  const date = new Date(dateString)
  
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000)
  const thisWeek = new Date(today.getTime() - 7 * 24 * 60 * 60 * 1000)
  const thisMonth = new Date(today.getFullYear(), now.getMonth(), 1)
  
  if (date >= today) {
    return '今天'
  } else if (date >= yesterday) {
    return '昨天'
  } else if (date >= thisWeek) {
    return '本周'
  } else if (date >= thisMonth) {
    return '本月'
  } else {
    return formatAbsoluteTime(dateString, 'date')
  }
}
